<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-input
              size="medium"
              v-model="foodName"
              placeholder="查询"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              size="small"
              type="primary"
              icon="el-icon-search"
              @click="getRecord()"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item label="">
            <el-button
              size="small"
              type="warning"
              @click="notEmpty"
              icon="el-icon-delete-solid"
              >清空</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="addition(1)"
              icon="el-icon-circle-plus-outline"
              >新增</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="24">
        <el-table
          :data="tableData"
          v-loading="loadFlag"
          border
          style="width: 100%"
        >
          <el-table-column type="index" width="70" label="序号" align="center">
          </el-table-column>
          <el-table-column prop="title" label="标题" width="" align="center">
          </el-table-column>

          <el-table-column prop="date" label="时间" align="center">
          </el-table-column>
          <el-table-column label="附件" align="center">
            <template #default="scope">
              <el-image
                class="table-td-thumb"
                :src="scope.row.file"
                :preview-src-list="[scope.row.file]"
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" align="center">
          </el-table-column>

          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <el-button size="mini" @click="editorPara(scope.row, 2)"
                >编辑</el-button
              >
              <el-button size="mini" type="danger" @click="deleted(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagingClass">
          <el-pagination
            :page-sizes="m_page.sizes"
            :page-size="m_page.size"
            :current-page="m_page.number"
            @size-change="m_handleSizeChange"
            @current-change="m_handlePageChange"
            layout="total,sizes,prev, pager, next"
            background
            :total="m_page.totalElements"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      :title="single"
      width="35%"
      v-model="plassets"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="titlebar">
          <el-input style="width: 300px" v-model="form.titlebar"></el-input>
        </el-form-item>
        <el-form-item label="时间" prop="dates">
          <el-date-picker
            style="width: 300px"
            v-model="form.dates"
            type="date"
            placeholder="选择日期"
            format="YYYY 年 MM 月 DD 日"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            accept=".jpeg,.jpg,.gif,.png"
            action="api/files"
            list-type="picture-card"
            :file-list="productImgs"
            :limit="1"
            :on-exceed="handleExceed"
            :on-preview="handlePictureCardPreview"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove"
            :headers="ToHeader"
          >
            <i class="el-icon-plus"></i>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img style="width: 100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="备注" prop="newnotes">
          <el-input
            type="textarea"
            :rows="2"
            style="width: 300px"
            placeholder="请输入内容"
            v-model="form.newnotes"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button @click="plassets = false">取 消</el-button>
          <el-button type="primary" v-if="under == 1" @click="determine('form')"
            >确 定</el-button
          >

          <el-button @click="hardware('form')" v-if="under == 2" type="primary"
            >编辑 确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";
export default {
  data() {
    return {
      loadFlag: false, //加载flag
      dialogImageUrl: "",
      productImgs: [],
      dialogVisible: false,
      form: {
        titlebar: "",
        dates: "",
        newnotes: "",
      },
      rules: {
        titlebar: [
          { required: true, message: "请输入标题", trigger: "change" },
        ],
        dates: [{ required: true, message: "请选择时间", trigger: "change" }],
      },
      foodName: "",
      tableData: [],
      plassets: false,
      under: 1,
      single: "",
      m_page: {
        sizes: [10, 20, 40, 50, 100], //每页最大显示数
        size: 10,
        totalElements: 0,
        totalPages: 3,
        number: 1,
      },
      headerObj: "",
      ToHeader: {
        Authorization: "",
      }, //上传图片请求头
    };
  },
  created() {
    let str = sessionStorage.getItem("token");
    this.headerObj = `Bearer ${str}`;
    this.ToHeader["Authorization"] = `Bearer ${str}`;
  },
  beforeMount() {
    this.getRecord();
  },
  methods: {
    onSubmit() {},
    //删除
    deleted(row) {
      // console.log(row);
      let into = row;
      this.$confirm("确认删除该汇款凭证?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post(
              `api/serial/RemittanceVoucher`,
              {
                id: into.id,
                isDelete: 1,
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then(() => {
              // console.log(res);
              this.getRecord();
              this.$message.success("删除成功");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //编辑
    hardware(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.$axios
            .post(
              `api/serial/RemittanceVoucher`,
              {
                id: this.underID,
                title: this.form.titlebar, //标题
                date: dayjs(this.form.dates).format("YYYY-M-D"), //时间
                file: this.dialogImageUrl, //图片
                remarks: this.form.newnotes, //备注
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then((res) => {
              console.log(res);
              this.$message({
                message: "编辑成功",
                type: "success",
              });
              this.plassets = false;
              this.getRecord();
            })
            .catch(() => {
              this.$message.error("编辑失败");
            });
        } else {
          this.$message({
            message: "信息未填全",
            type: "warning",
          });
          return false;
        }
      });
    },
    editorPara(row, index) {
      this.under = index;
      this.underID = row.id;
      this.single = "编辑汇款凭证";
      this.plassets = true;
      // console.log(row);
      let arr = row;
      console.log(arr);
      this.form.titlebar = arr.title;
      this.form.dates = arr.date;
      let picture = [];
      if (arr.file) {
        picture[0] = {
          url: arr.file,
        };
      }
      this.productImgs = picture;
      this.dialogImageUrl = arr.file;
      console.log(this.dialogImageUrl);
      this.form.newnotes = arr.remarks;
    },

    //新增
    determine(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.$axios
            .post(
              `api/serial/RemittanceVoucher`,
              {
                title: this.form.titlebar, //标题
                date: dayjs(this.form.dates).format("YYYY-M-D"), //时间
                file: this.dialogImageUrl, //图片
                remarks: this.form.newnotes, //备注
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then((res) => {
              console.log(res);
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.plassets = false;
              this.getRecord();
            })
            .catch(() => {
              this.$message.error("保存失败");
            });
        } else {
          // console.log("error submit!!");
          this.$message({
            message: "信息未填全",
            type: "warning",
          });
          return false;
        }
      });
      dayjs(this.form.dates).format("YYYY-M-D");
    },
    resetForm(form) {
      this.$refs[form].resetFields();
    },
    addition(index) {
      this.under = index;
      this.single = "新增汇款凭证";
      this.plassets = true;
      this.form.titlebar = "";
      this.form.dates = "";
      this.productImgs = [];
      this.dialogImageUrl = "";
      this.form.newnotes = "";
      // this.resetForm();
    },
    notEmpty() {
      this.foodName = "";
      this.getRecord();
    },
    //获取数据
    getRecord() {
      this.loadFlag = true;
      this.$axios({
        methods: "GET",
        url: "api/serial/RemittanceVoucher",
        headers: {
          Authorization: this.headerObj,
        },
        params: {
          pageSize: this.m_page.size,
          pageIndex: this.m_page.number,
          query: {
            title: this.foodName,
          },
        },
      }).then((res) => {
        //  count: this.m_page.totalElements
        ({ data: this.tableData, count: this.m_page.totalElements } = res.data);
        // this.tableData.forEach((item) => {
        //   item.startDate = dayjs(item.startDate).format("YYYY-M-D");
        // });
        this.loadFlag = false;
      });
    },
    //页码
    m_handlePageChange(currPage) {
      this.m_page.number = currPage;
      this.getRecord();
    },
    m_handleSizeChange(currSize) {
      this.m_page.size = currSize;
      this.getRecord();
    },
    //上传
    //预览图片
    handlePictureCardPreview() {
      // console.log(file);
      // if (file.response.data) {
      //   this.dialogImageUrl = file.response.data;
      // }

      this.dialogVisible = true;
    },
    handleChangePic(productImgs) {
      console.log(productImgs);
      this.hideUploadEdit = productImgs.length >= 1;
    },
    // 上传成功
    handleAvatarSuccess(res) {
      // console.log(res);
      // console.log(file);
      this.dialogImageUrl = res.data;
      // console.log(this.dialogImageUrl);
    },
    handleExceed(files, fileList) {
      //图片上传超过数量限制
      this.$message.error("上传图片不能超过1张!");
      console.log(files, fileList);
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error("上传图片只能是 JPG 格式!");
      // }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    handleRemove(file, productImgs) {
      console.log(file, productImgs);
      this.dialogImageUrl = "";
      // this.hideUploadEdit = productImgs.length >= 1;
    },
  },
};
</script>

<style scoped>
.table-td-thumb {
  display: block;
  margin: auto;
  width: 60px;
  height: 60px;
}
</style>